package com.pet.server.ext.action.request;

import java.util.Date;

import com.pet.server.ext.ActionBase;
import com.pet.server.ext.ApiError;
import com.pet.server.ext.BeanToJson;
import com.pet.server.ext.Result;
import com.pet.server.ext.constants.BaseAttribute;
import com.pet.server.ext.data.Option;
import com.pet.server.ext.data.RequestInfo;
import com.pet.server.ext.data.UserInfo;
import com.pet.server.ext.service.UserService;
import com.pet.server.ext.util.NumberUtil;
import com.pet.server.ext.util.Parameters;
import com.pet.server.ext.util.StringUtil;

public class Add extends ActionBase{

	public RequestInfo request;
	
	public Add(){
		 needCheckAuth =true;
	}
	
	@Override
	public void initParameters(Parameters params) throws ApiError {	
		request = new RequestInfo();
		String question = params.getFieldValue("question");
		Integer score = NumberUtil.getInteger(params.getFieldValue("score"),0);
		if(StringUtil.isEmpty(question)){
			throw ApiError.Type.INVALID_PARAM.toException();
		}
		request.create_time=new Date();
		request.state=BaseAttribute.LOGIC_FALSE;
		request.user_id=user.user_id;
		request.question=question;
		request.nick_name=user.nick_name;
		request.score=score;
		request.type=params.getFieldValue("type");
		int i=0;
		String option_text=params.getFieldValue("option"+i);
		while(!StringUtil.isEmpty(option_text)){
			Option op = new Option();
			op.option_text=option_text;
			request.options.add(op);
			i++;
			option_text=params.getFieldValue("option"+i);
		}
		
	}
	@Override
	public Result invokeService() throws ApiError {
		UserService userService = new UserService();
	    UserInfo u = userService.findUserInfoById(user.user_id);
		if(u.score<request.score){
			throw ApiError.Type.LOGIC_ERROR.toException("所属积分小于悬赏积分!");
		}
	    userService.saveRequestInfo(request);
	    if(BaseAttribute.diaoc.equals(request.type)){
           for(Option op:request.options){
        	   op.request_id=request.id;
        	   userService.saveOption(op);
           }	    	
	    }
	    userService.subScore(user.user_id, request.score);
	    request.nick_name=u.nick_name;
	    request.ico_path=u.ico_path;
		Result result = new Result();
		result.put("data",BeanToJson.objectToJson(request));
	    return result;
	}
}
